﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;

namespace YArchitech.HVAC
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class HYByRectangleFittingConnect : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			Transaction transaction = null;
			Result result;
			try
			{
				if (commandData == null)
				{
					throw new System.ArgumentNullException("commandData", "is null");
				}
				UIDocument activeUIDocument = commandData.Application.ActiveUIDocument;
				Document document = activeUIDocument.Document;
				Selection selection = activeUIDocument.Selection;
				new List<Element>();
				IList<Duct> list = new List<Duct>();
				ISelectionFilter selectionFilter = new DuctSelectionFilter();
				HYDuctConnect hyductConnect = new HYDuctConnect();
				string text = "框选连接";
				for (;;)
				{
					list.Clear();
					RevitVersionFuncs.ClearSelection(selection);
					transaction = new Transaction(document, text);
					transaction.Start();
					foreach (Element element in selection.PickElementsByRectangle(selectionFilter, "请选择风管"))
					{
						if (element != null)
						{
							list.Add(element as Duct);
						}
					}
					if (2 == list.Count)
					{
						if (!hyductConnect.NewElbowFitting(list) && !hyductConnect.NewTransitionFitting(list) && !hyductConnect.NewLHWFitting(list))
						{
							MessageBox.Show("连接失败", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
						}
					}
					else if (3 == list.Count)
					{
						if (!hyductConnect.NewTeeFitting(list))
						{
							MessageBox.Show("连接失败", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
						}
					}
					else if (4 == list.Count)
					{
						if (!hyductConnect.NewCrossFitting(list, null))
						{
							MessageBox.Show("连接失败", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
						}
					}
					else
					{
						MessageBox.Show("请选择不多于四个风管", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
					}
					document.Regenerate();
					transaction.Commit();
				}
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex)
			{
				message = ex.Message;
				result = Autodesk.Revit.UI.Result.Failed;
			}
			finally
			{
				TransactionStatus status = transaction.GetStatus();
                if ((int)status == 1)
				{
					transaction.Commit();
				}
                else if ((int)status == 5)
				{
					transaction.RollBack();
				}
			}
			return result;
		}
	}
}
